package com.talking.view.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.talking.App;
import com.talking.adapter.MessageAdapter;
import com.talking.bean.GroupBean;
import com.talking.bean.MessageBean;
import com.talking.databinding.FragmentMsgBinding;
import com.talking.presenter.GroupPresenter;
import com.talking.presenter.HistoryPresenter;
import com.talking.presenter.MessagePresenter;
import com.talking.view.ChatActivity;
import com.talking.view.ChatGroupActivity;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MsgFragment extends Fragment {
    private FragmentMsgBinding binding;
    private final List<MessageBean> data=new ArrayList<>();
    private MessageAdapter adp;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentMsgBinding.inflate(inflater, container, false);
        adp=new MessageAdapter(requireActivity(),data);
        binding.fragmentMsgList.setAdapter(adp);
        binding.fragmentMsgList.setOnItemClickListener((parent, view, position, id) -> {
            MessageBean bean = data.get(position);
            String message = App.sp.getString("message", "");
            if (message.equals("")){
                refresh();
            }else {
                try {
                    JSONArray ja = new JSONArray(message);
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        if (jo.getString("accepterAccount").equals(App.sp.getString("account",""))&& jo.getString("senderAccount").equals(bean.account)){
                            MessagePresenter.deleteMsg(jo.getString("id"), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                refresh();
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refresh();
                            }
                        });
                        }
                    }
                    JSONArray ja1 = new JSONArray();
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        if (!(jo.getString("accepterAccount").equals(App.sp.getString("account",""))&& jo.getString("senderAccount").equals(bean.account))){
                           ja1.put(jo);
                        }
                    }
                    @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                    edit.putString("message",ja1.toString());
                    edit.apply();
                    if (bean.type.equals("group")){
                        GroupPresenter.queryGroupById(bean.account, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) { e.printStackTrace(); }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                requireActivity().runOnUiThread(() -> {
                                    try {
                                        String res = response.body().string();
                                        JSONObject jo = new JSONObject(res);
                                        App.groupBean=new GroupBean(jo.getString("name"),jo.getString("icon"),jo.getString("id"));
                                        startActivityForResult(new Intent(requireActivity(), ChatGroupActivity.class),3);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        });
                    }
                    if (bean.type.equals("user")){
                        App.chatingWith=bean.account;
                        startActivityForResult(new Intent(requireActivity(), ChatActivity.class),3);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        binding.fragmentMsgList.setOnItemLongClickListener((parent, view, position, id) ->{
            MessageBean bean = data.get(position);
            if (bean.type.equals("user")) {
               AlertDialog.Builder dialog = new AlertDialog.Builder(requireActivity());
               dialog.setTitle("确认").setMessage("是否删除聊天记录?此操作会删除\n1.对方的聊天记录\n2.双方的通知消息\n3.未接受的文件\n\n已保存的文件不会删除。/doge").setPositiveButton("删除", (dialog1, which) -> {
                   HistoryPresenter.deleteAll(App.sp.getString("account", ""), data.get(position).account, new Callback() {
                       @Override
                       public void onFailure(@NotNull Call call, @NotNull IOException e) {
                           refresh();
                       }

                       @Override
                       public void onResponse(@NotNull Call call, @NotNull Response response) {
                           refresh();
                       }
                   });
                   String message = App.sp.getString("message", "");
                   try {
                       JSONArray ja = new JSONArray(message);
                       for (int i = 0; i < ja.length(); i++) {
                           JSONObject jo = ja.getJSONObject(i);
                           if (jo.getString("accepterAccount").equals(App.sp.getString("account", "")) && jo.getString("senderAccount").equals(bean.account) || jo.getString("senderAccount").equals(App.sp.getString("account", "")) && jo.getString("accepterAccount").equals(bean.account)) {
                               MessagePresenter.deleteMsg(jo.getString("id"), new Callback() {
                                   @Override
                                   public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                       e.printStackTrace();
                                   }

                                   @Override
                                   public void onResponse(@NotNull Call call, @NotNull Response response) {
                                   }
                               });
                           }
                       }
                       JSONArray ja1 = new JSONArray();
                       for (int i = 0; i < ja.length(); i++) {
                           JSONObject jo = ja.getJSONObject(i);
                           if (!(jo.getString("accepterAccount").equals(App.sp.getString("account", "")) && jo.getString("senderAccount").equals(bean.account))) {
                               ja1.put(jo);
                           }
                       }
                       @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                       edit.putString("message", ja1.toString());
                       edit.apply();
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }).setNegativeButton("", null).show();
            }
            return true;
        });
        refresh();
        return binding.getRoot();
    }
    private void refresh() {
        MessagePresenter.querySingle(App.sp.getString("account",""), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                requireActivity().runOnUiThread(() -> {
                    String msg = App.sp.getString("message", "");
                    HashMap<String,Integer> hash=new HashMap<>();
                    if (!msg.equals("")){
                        try {
                            data.clear();
                            JSONArray ja = new JSONArray(msg);
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo = ja.getJSONObject(i);
                                if (jo.getString("type").equals("消息通知")&&jo.getString("accepterAccount").equals(App.sp.getString("account",""))){
                                    Integer value = hash.get(jo.getString("senderAccount"));
                                    if (value!=null){
                                        hash.put(jo.getString("senderAccount"),1+value);
                                    }else {
                                        hash.put(jo.getString("senderAccount"),1);
                                    }
                                }
                            }
                            String res = response.body().string();
                            JSONArray ja1 = new JSONObject(res).getJSONArray("data");
                            for (int i = 0; i < ja1.length(); i++) {
                                JSONObject jo = ja1.getJSONObject(i);
                                String account;
                                if (jo.getString("type").equals("用户")) {
                                    if (jo.getString("senderAccount").equals(App.sp.getString("account", ""))) {
                                        account = jo.getString("accepterAccount");
                                    } else {
                                        account = jo.getString("senderAccount");
                                    }
                                    String newmsg = String.valueOf(hash.get(account));//未读消息数量
                                    if (newmsg.equals("null")) {
                                        newmsg = "0";
                                    }
                                    if (jo.getString("content_type").equals("文件")) {
                                        String fileName = jo.getString("content");
                                        data.add(new MessageBean(account, fileName.substring(fileName.lastIndexOf("-") + 1), newmsg,"user"));
                                    } else {
                                        data.add(new MessageBean(account, jo.getString("content"), newmsg,"user"));
                                    }
                                }else if (jo.getString("type").equals("群组")) {
                                    if (jo.getString("content_type").equals("文件")) {
                                        String fileName = jo.getString("content");
                                        data.add(new MessageBean(jo.getString("accepterAccount"), fileName.substring(fileName.lastIndexOf("-") + 1), "0","group"));
                                    } else {
                                        data.add(new MessageBean(jo.getString("accepterAccount"), jo.getString("content"), "0","group"));
                                    }
                                }
                            }
                            adp.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==3){
            refresh();
        }
    }
}